import { DragItem } from '@/views/DragDemo/components/types';
import React, { useRef } from 'react';
import { useDrag, useDrop } from 'react-dnd';

interface GragItemProps extends React.HTMLAttributes<HTMLDivElement> {
    item?: any,
    index: number;
    moveItem: (fromIndex: number, toIndex: number) => void;
    children: any;
}

const GragItem: React.FC<GragItemProps> = ({ item, index, moveItem, ...rest }) => {
    const ref = useRef<HTMLDivElement>(null);

    const [{ isDragging }, drag] = useDrag({
        type: 'GRID_ITEM',
        item: {
            index,
            // id: item.id,
            // type: 'GRID_ITEM'
        },
        collect: (monitor) => ({
            isDragging: monitor.isDragging(),
        }),
    });

    const [, drop] = useDrop({
        accept: 'GRID_ITEM',
        // drop: (item, monitor) => {
        //     console.log(30, item, monitor)
        // },
        hover: (dragItem: DragItem, monitor) => {
            // return
            if (!ref.current) return;

            // TODO: 怎么搞

            const dragIndex = dragItem.index;
            const hoverIndex = index;

            if (dragIndex === hoverIndex) return;

            // 获取元素位置信息
            const hoverBoundingRect = ref.current.getBoundingClientRect();
            const hoverMiddleX = (hoverBoundingRect.right - hoverBoundingRect.left) / 2;
            const hoverMiddleY = (hoverBoundingRect.bottom - hoverBoundingRect.top) / 2;
            const clientOffset = monitor.getClientOffset();

            // 计算鼠标在目标元素内的相对位置
            const hoverClientX = clientOffset.x - hoverBoundingRect.left;
            const hoverClientY = clientOffset.y - hoverBoundingRect.top;

            // 方向判断逻辑
            const isMovingRight = dragIndex < hoverIndex;
            const isMovingLeft = dragIndex > hoverIndex;
            const isMovingDown = dragIndex < hoverIndex;
            const isMovingUp = dragIndex > hoverIndex;

            // 水平方向判断
            if (Math.abs(hoverClientX - hoverMiddleX) > Math.abs(hoverClientY - hoverMiddleY)) {
                // 水平移动为主
                if (isMovingRight && hoverClientX < hoverMiddleX) return;
                if (isMovingLeft && hoverClientX > hoverMiddleX) return;
            }
            // 垂直方向判断
            else {
                // 垂直移动为主
                if (isMovingDown && hoverClientY < hoverMiddleY) return;
                if (isMovingUp && hoverClientY > hoverMiddleY) return;
            }

            // console.log(45, dragIndex, hoverIndex)

            moveItem(dragIndex, hoverIndex);
            dragItem.index = hoverIndex;
        },
    });

    drag(drop(ref));

    return (
        <div
            ref={ref}
            className={`w100 grid-item ${isDragging ? 'dragging' : ''}`}
            style={{
                opacity: isDragging ? 0.5 : 1,
                cursor: 'move',
            }}
            {...rest}
        >
        </div>
    );
};

export default GragItem;